package com.lenovo.smarttraffic.ui.activity;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.api.VolleyCallBack;
import com.lenovo.smarttraffic.util.VolleyUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Caleb.F
 * on 2019-09-26
 * at 9:29
 */
public class RoadActivity extends BaseActivity {
    private BarChart mRoadManagerBarchat;
    private Map<String, List<Integer>> map = new HashMap<>();
    private Map<String, List<Integer>> dataSetMap = new HashMap<>();
    private List<Integer> Entrylist = new ArrayList<>();
    private static final String TAG = "RoadActivity";
    private Timer timer;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mProgressDialog=new ProgressDialog(this);
        mProgressDialog.setMessage("加载中，请稍后....");
        initView();
        mProgressDialog.show();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        }, 0, 3000);

    }

    private void initView() {
        initToolBar("路况分析");
        mRoadManagerBarchat = findViewById(R.id.my_bar_chat);
        inchat();
    }

    private void inchat() {
        XAxis xAxis = mRoadManagerBarchat.getXAxis();
        xAxis.setDrawGridLines(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1);
        xAxis.setLabelCount(8);
        xAxis.setAxisMinimum(0);
        xAxis.setAxisMaximum(7);
        //此时才是居中
        xAxis.setCenterAxisLabels(false);
        xAxis.setXOffset(5f);
        final String[] strings = new String[]{
                "周一",
                "周二",
                "周三",
                "周四",
                "周五",
                "周六",
                "周日"
        };
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                int index = Math.round(value);
                if (index < 0 || index >=strings.length || index != (int) value) {
                    return "";
                }
                return strings[index];
            }
        });
       final String[] strings1 = new String[]{
                "畅通",
                "缓行",
                "一般拥堵",
                "中度拥堵",
                "严重拥堵", "严重拥堵"
        };
        YAxis axisLeft = mRoadManagerBarchat.getAxisLeft();
        axisLeft.setEnabled(true);
        axisLeft.setGranularity(1);
        axisLeft.setAxisMinimum(0);
        axisLeft.setAxisMaximum(5);
        axisLeft.setLabelCount(5);
        axisLeft.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                int index = Math.round(value);
                if (index < 0 || index >=strings.length || index != (int) value) {
                    return "";
                }
                return strings1[index];
            }
        });
        YAxis axisRight = mRoadManagerBarchat.getAxisRight();
        axisRight.setEnabled(true);
        axisRight.setLabelCount(5);
        axisRight.setAxisMinimum(0);
        axisRight.setAxisMaximum(5);

        Legend legend1 = mRoadManagerBarchat.getLegend();
        legend1.setEnabled(true);
        legend1.setPosition(Legend.LegendPosition.ABOVE_CHART_CENTER);
        legend1.setTextSize(15f);
    }

    @Override
    protected int getLayout() {
        return R.layout.actiivity_road;
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case 1:
                    getData1();
                    break;
            }
            return true;
        }
    });

    private void getData1() {
        ArrayList<List<Integer>> arrayLists = new ArrayList<>();
        for (int j = 1; j < 8; j++) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < 7; i++) {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("RoadId", j);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                VolleyUtil.post("GetRoadStatus.do", jsonObject, new VolleyCallBack() {
                    @Override
                    public void onSucceess(JSONObject jsonObject, String response) {
                        if ("S".equals(jsonObject.optString("RESULT", "F"))) {
                            list.add(jsonObject.optInt("Status"));
                            if (list.size() == 7) {
                                arrayLists.add(list);
                                if (arrayLists.size() == 7) {
                                    for (int x = 1; x < 8; x++) {
                                        map.put("roadId" + x, arrayLists.get(x - 1));
                                    }
                                    drawData();
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(String onError) {

                    }
                });
            }
        }
    }

    private void drawData() {
        mProgressDialog.dismiss();
        ArrayList<BarDataSet> barDataSets = new ArrayList<>();
        String[] strings = new String[]{
                "学院路",
                "联想路",
                "医院路",
                "幸福路",
                "环城快速路",
                "环城高速",
                "停车场"
        };
        Integer[] colors = new Integer[]{
                Color.parseColor("#C33733"),
                Color.parseColor("#2F4554"),
                Color.parseColor("#70A8AF"),
                Color.parseColor("#70A8AF"),
                Color.parseColor("#D48265"),
                Color.parseColor("#D48265"),
                Color.parseColor("#749F83")
        };

        for (int x = 1; x < 8; x++) {
            ArrayList<BarEntry> barEntries = new ArrayList<>();
            for (int i = 0; i < 7; i++) {
                BarEntry barEntry = new BarEntry(i, map.get("roadId" + x).get(i));
                barEntries.add(barEntry);
            }
            BarDataSet barDataSet = new BarDataSet(barEntries, strings[x - 1]);
            barDataSet.setColor(colors[x-1]);
            barDataSet.setLabel(strings[x-1]);
            barDataSet.setDrawValues(false);
            barDataSets.add(barDataSet);
        }
        BarData barData=new BarData(barDataSets.get(0));
        barData.addDataSet(barDataSets.get(1));
        barData.addDataSet(barDataSets.get(2));
        barData.addDataSet(barDataSets.get(3));
        barData.addDataSet(barDataSets.get(4));
        barData.addDataSet(barDataSets.get(5));
        barData.addDataSet(barDataSets.get(6));
        mRoadManagerBarchat.setData(barData);
        barData.setBarWidth(0.1f);
        barData.groupBars(0.0f, 0.3f, 0.0f);
        mRoadManagerBarchat.notifyDataSetChanged();
        mRoadManagerBarchat.invalidate();
    }

    @Override
    protected void onStop() {
        super.onStop();
        timer.cancel();
    }
}
